package com.foodost.cwpstrokes;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.FinalDb;
import net.tsz.afinal.FinalDb.DbUpdateListener;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;


public class CWPStrokesModel {

    private static final String TAG = "CWPStrokesModel";
    private FinalDb db;
    private String DATABASES_DIR="/data/data/com.foodost.cwpstrokes/databases";
    public  FinalDb getFinalDb(Context context){
        if(db == null){
            db = FinalDb.create(context, Constants.DB_NAME, false, Constants.DB_VERSION, dbListener);
        }
        return db;
    }
    
    private  DbUpdateListener dbListener = new DbUpdateListener() {
        
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            if(newVersion > oldVersion){
                Log.d(TAG, "newVersion = " + newVersion);
            }
        }
    };
    
    public CWPStrokesModel(Context context){
    }
  
    public  void copyDatabaseFile(Context context, boolean isfored) {  
              
            File dir = new File(DATABASES_DIR);  
            if (!dir.exists() || isfored) {  
                try {  
                    dir.mkdir();  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
              
            File dest = new File(dir, Constants.DB_NAME);  
            if(dest.exists() && !isfored){  
                return ;  
            }  
              
            try {  
                if(dest.exists()){  
                    dest.delete();  
                }  
                dest.createNewFile();     
                InputStream in = context.getResources().openRawResource(R.raw.cwpstrokes);  
                int size = in.available();  
                byte buf[] = new byte[size];  
                in.read(buf);  
                in.close();  
                FileOutputStream out = new FileOutputStream(dest);  
                out.write(buf);  
                out.close();  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        } 
    
    //初始化level数据库中数据或更新数据
    public void getHanziListByGrage(Context context,int grage,boolean isUpdate){
        List<Hanzi> hanziList = new ArrayList<Hanzi>();
        hanziList = getFinalDb(context).findAllByWhere(Hanzi.class, "grage = " + grage);
        Log.v(TAG, "hanziList size = " + hanziList.size());
        Collections.shuffle(hanziList);
        List<Hanzi> selectedList = hanziList.subList(0, 20*(grage + 1));
        StringBuilder strBuilder = new StringBuilder();
        for(Hanzi hanzi : selectedList){
            strBuilder.append(hanzi.getWord()+",");
        }
        Level level = null;
        if(isUpdate){
            level = getLevel(context, grage);
        }else{
            level = new Level();
        }
        level.setCount(0);
        level.setGrage(grage);
        level.setHanziList(strBuilder.toString());
        level.setWordIndex(0);
        level.setPass(false);
        level.setRate(0);
        level.setOpen(true);
        if(isUpdate){
            getFinalDb(context).update(level); 
        }else{
            getFinalDb(context).save(level);
        }
    }
    //获取汉字对应笔画map
    public Map<String,Integer> getWordStrokeMapByGrage(Context context,List<String> stringList,int grage){
        List<Hanzi> hanziList = getFinalDb(context).findAllByWhere(Hanzi.class, "grage = " + grage);
        Map<String,Integer> wordStrokeMap = new HashMap<String, Integer>();
        for(Hanzi hanzi : hanziList){
            if(stringList.contains(hanzi.getWord())){
                wordStrokeMap.put(hanzi.getWord(), hanzi.getStroke());
            }
        }
        return wordStrokeMap;
        
    }
    //判断level表中是否有记录
    public boolean hasLevelData(Context context){
        List<Level> levelList = getFinalDb(context).findAll(Level.class);
        if(levelList.size() > 0){
            Log.d(TAG, "hasLevelData");
            return true;
        }
        return false;
    }
    //更新Level汉字索引
    public void saveLevelWordIndex(int wordIndex,int grage){
        List<Level> levelList = db.findAllByWhere(Level.class, "grage = " + grage);
        if(levelList.size() > 0){
            Log.d(TAG, "saveLevelWordIndex > 0");
            Level level = levelList.get(0);
            level.setWordIndex(wordIndex);
            db.update(level);
        }
    }
    //获取level汉字索引
    public int getWordIndexFromLevel(Context context,int grage){
        Level level = getLevel(context, grage);
        if(level != null){
            return level.getWordIndex(); 
        }
        return 0;
    }
    //更新汉字笔画数正确数总数
    public void saveLevelWordCount(int count,int grage){
        List<Level> levelList = db.findAllByWhere(Level.class, "grage = " + grage);
        if(levelList.size() > 0){
            Log.d(TAG, "saveLevelWordCount > 0");
            Level level = levelList.get(0);
            level.setCount(count);
            db.update(level);
        }
    }
    //获取正确数总数
    public int getWordRightCountFromLevel(Context context,int grage){
        Level level = getLevel(context, grage);
        if(level != null){
            return level.getCount();
        }
        return 0;
    }
    //获取相应游戏级别level数据，无，返回null
    public Level getLevel(Context context,int grage){
        List<Level> levelList = getFinalDb(context).findAllByWhere(Level.class, "grage = " + grage);
        if(levelList.size() > 0){
           return levelList.get(0); 
        } 
        return null;
    }
    
    //更新用户打开最高等级记录
    public void setGragestFromUser(Context context,String username,int gragest){
        List<User> userList = new ArrayList<User>();
        if(username == null){
            userList = getFinalDb(context).findAll(User.class);
        }else{
            userList = getFinalDb(context).findAllByWhere(User.class, "username like '" + username.trim() +"%'");
        }
        if(userList.size() > 0){
            User user = userList.get(0);
            if(gragest > user.getGragest()){
                user.setGragest(gragest);
                getFinalDb(context).update(user);
            }
        }else{
            User user = new User();
            user.setUsername(username);
            user.setGragest(gragest);
            getFinalDb(context).save(user);
        }
    }
    
    
    
}
